package com.atsongyr.springcloud.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author songyurui
 */
@Service
public class PaymentService {

    /**
     * 正常访问，肯定ok
     * @param id
     * @return
     */
    public String paymentInfo_OK(Integer id) {
        return "线程池："+Thread.currentThread().getName() + " PaymentInfo_ok,id:"
                + id
                + "\t"+"Hystrix使用的是tomcat的线程池";
    }

    /**
     * 超时测试熔断
     * fallbackMethod出问题后兜底的方法
     * HystrixProperty 意思为这个线程峰值为三秒，三秒以内走自己的业务逻辑，超过三秒走paymentInfo_TimeoutHandler
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeoutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")})
    public String paymentInfo_Timeout(Integer id) {
        int sleepTime = 3;
        try {
            TimeUnit.SECONDS.sleep(sleepTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "线程池："+Thread.currentThread().getName() + " paymentInfo_Timeout,id:"
                + id
                + "\t"+"耗时(秒)"+sleepTime;
    }

    public String paymentInfo_TimeoutHandler(Integer id){
        return "线程池："+Thread.currentThread().getName() + "系统繁忙，请稍后再试paymentInfo_TimeoutHandler,id:"
                + id
                + "\t"
                + "(/ω＼)";
    }
}
